package com.qiyee.dalligent.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

public class BarcodeGenerator {

    private static final Integer CODE_WIDTH = 30;                 // 基础属性：二维码宽度，单位像素
    private static final Integer CODE_HEIGHT = 20;                // 基础属性：二维码高度，单位像素
    private static final Integer FRONT_COLOR = 0x000000;           // 基础属性：二维码前景色，0x000000 表示黑色
    private static final Integer BACKGROUND_COLOR = 0xFFFFFF;      // 基础属性：二维码背景色，0xFFFFFF 表示白色

    public static void main(String[] args) throws Exception {
        // 重复
        String qrMessage = "8894796215296711"+new Random().nextInt(100);
        exportToExcel(qrMessage, getBarCodeByCode(qrMessage),2);
    }

    private static byte[] getBarCodeByCode(String qrMessage) throws Exception {
        //设置生成条形码的内容（注：条形码信息一定要按照格式，如随便一个商品上的条形码都行，但必须是EAN_13格式）


        // EncodeHintType：指定和控制码生成器的一些参数的类
        Map<EncodeHintType, Object> typeObjectHashMap = new HashMap<EncodeHintType, Object>();
        // 设置编码
        typeObjectHashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置容错等级
        typeObjectHashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置边距，默认为5
        typeObjectHashMap.put(EncodeHintType.MARGIN, 3);

        // MultiFormatWriter:用于写入条形码或二维码
        Code128Writer multiFormatWriter = new Code128Writer();
        BitMatrix bitMatrix = multiFormatWriter
            .encode(qrMessage, BarcodeFormat.CODE_128, CODE_WIDTH, CODE_HEIGHT, typeObjectHashMap);

        // java.awt.image.BufferedImage：把条形码信息转换为图像信息
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ;

         return bufferedImageToByteArray(bufferedImage);
        //
    }

    public static byte[] bufferedImageToByteArray(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }
    public static void exportToExcel(String fileName,byte[] bytes,int i) throws Exception{
        String name = fileName + ".xlsx";
        Workbook workbook = new XSSFWorkbook(); // 创建工作簿
        Sheet sheet = workbook.createSheet("Barcodes"); // 创建工作表
        // 创建标题行的样式

        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        Row row = sheet.createRow(0); // 创建第一行
        Cell cell = row.createCell(0); // 创建单元格
        Cell cell2 = row.createCell(2); // 创建单元格
        cell.setCellValue("Barcode Image"); // 设置单元格内容
        cell2.setCellValue("Barcode Image2"); // 设置单元格内容
        // 设置单元格样式
        CellStyle style = workbook.createCellStyle();
        // 设置字体
        Font headerFont = workbook.createFont();
        headerFont.setBold(true); // 设置为加粗
        headerFont.setFontHeightInPoints((short)16);
        style.setFont(headerFont);
        sheet.setDefaultColumnWidth(30);
        sheet.setDefaultRowHeightInPoints(24);
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        style.setWrapText(true);
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); // 背景颜色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充模式
        cell.setCellStyle(style);
        cell.setAsActiveCell();
        cell2.setCellStyle(style);
        cell2.setAsActiveCell();
        FileOutputStream outputStream = new FileOutputStream(name);
        for (int i1 = 0; i1 < i; i1++) {
            Drawing drawing = sheet.createDrawingPatriarch();
            // int col1 设置图片开始的列索引, int row1, int col2, int row2
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, i1*2 , 1, i1*2  + 1, 2);
            drawing.createPicture(anchor,
                workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG));

            /*// 插入条码图片
            int pictureIndex =
                workbook.addPicture(Files.readAllBytes(Paths.get(barcodeFilePath)), Workbook.PICTURE_TYPE_PNG);
            CreationHelper helper = workbook.getCreationHelper(); // 创建帮助器
            Drawing drawing = sheet.createDrawingPatriarch();
            // XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 0, 1);
            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setCol1(0+i1);// 设置图片开始的列索引
            anchor.setRow1(1);// 设置图片开始的行索引
            anchor.setCol2(1+i1);
            anchor.setRow2(2+i1);
            anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
            drawing.createPicture(anchor, pictureIndex).resize(); // 设置图片大小
*/
        }

        workbook.write(outputStream);
        // 保存Excel文件

        System.out.printf("filName:" + name);
        workbook.close(); // 关闭工作簿

    }
    // 条形码
    public static void exportToExcel(String qrMessage, HttpServletResponse response) throws Exception{
        byte[] bytes = getBarCodeByCode(qrMessage);
        int i=2;
        Workbook workbook = new XSSFWorkbook(); // 创建工作簿
        Sheet sheet = workbook.createSheet("Barcodes"); // 创建工作表
        // 创建标题行的样式

        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        Row row = sheet.createRow(0); // 创建第一行
        Cell cell = row.createCell(0); // 创建单元格
        Cell cell2 = row.createCell(2); // 创建单元格
        cell.setCellValue("Barcode Image"); // 设置单元格内容
        cell2.setCellValue("Barcode Image2"); // 设置单元格内容
        // 设置单元格样式
        CellStyle style = workbook.createCellStyle();
        // 设置字体
        Font headerFont = workbook.createFont();
        headerFont.setBold(true); // 设置为加粗
        headerFont.setFontHeightInPoints((short)16);
        style.setFont(headerFont);
        sheet.setDefaultColumnWidth(30);
        sheet.setDefaultRowHeightInPoints(24);
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        style.setWrapText(true);
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); // 背景颜色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充模式
        cell.setCellStyle(style);
        cell.setAsActiveCell();
        cell2.setCellStyle(style);
        cell2.setAsActiveCell();
        ServletOutputStream outputStream = response.getOutputStream();
        //FileOutputStream outputStream = (FileOutputStream)outputStream1;
        for (int i1 = 0; i1 < i; i1++) {
            Drawing drawing = sheet.createDrawingPatriarch();
            // int col1 设置图片开始的列索引, int row1, int col2, int row2
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, i1*2 , 1, i1*2  + 1, 2);
            drawing.createPicture(anchor,
                workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG));
        }
        outputXls(workbook,qrMessage,response);
        //workbook.write(outputStream);
        // 保存Excel文件

        //workbook.close(); // 关闭工作簿

    }

    // 处理数据流的时候
    public static void outputXls(Workbook workbook, String fileName, HttpServletResponse response) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        try {
            workbook.write(os);
            byte[] content = os.toByteArray();
            ByteArrayInputStream is = new ByteArrayInputStream(content);
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setHeader("Content-Type","application/msexcel");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName+".xlsx","utf-8"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                    bos.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                workbook.close();
                if (bis != null)
                    bis.close();
                if (bos != null)
                    bos.close();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
    public static void exportToExcel2(String qrMessage, HttpServletResponse response) throws Exception{

        int i=2;
        Workbook workbook = new XSSFWorkbook(); // 创建工作簿
        Sheet sheet = workbook.createSheet("Barcodes"); // 创建工作表
        // 创建标题行的样式

        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        Row row = sheet.createRow(0);
        List<String> cellList = new ArrayList<>(7);
        cellList.add("质检报告标题");
        cellList.add("质检编码");
        cellList.add("订单号");
        cellList.add("订单条形码");
        cellList.add("IMEI/SN码");
        cellList.add("IMEI/SN条形码");
        cellList.add("订单状态");
        cellList.add("下单时间");
        Font headerFont = workbook.createFont();
        headerFont.setBold(true); // 设置为加粗
        headerFont.setFontHeightInPoints((short)16);
        // 设置单元格样式
        CellStyle style = workbook.createCellStyle();
        CellStyle style2 = workbook.createCellStyle();
        style.setFont(headerFont);
        sheet.setDefaultColumnWidth(20);
        sheet.setDefaultRowHeightInPoints(30);
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style2.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        style2.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        style.setWrapText(true);
        style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex()); // 背景颜色
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充模式
        for (int i2 = 0; i2 < cellList.size(); i2++) {
            Cell cell = row.createCell(i2);
            cell.setCellStyle(style);
            cell.setCellValue(cellList.get(i2));
            cell.setAsActiveCell();
        }
        //FileOutputStream outputStream = (FileOutputStream)outputStream1;
        for (int i1 = 0; i1 < 10; i1++) {
            Row rowNext = sheet.createRow(i1+1);
            for (int i2 = 0; i2 < cellList.size(); i2++) {
                Cell cell = rowNext.createCell(i2);
                cell.setCellStyle(style2);
                String qrMessage1 = i1 + "_code"+i2;
                if (i2==3){
                    byte[] bytes = getBarCodeByCode(qrMessage1);
                    Drawing drawing = sheet.createDrawingPatriarch();
                    /*
                     * 参数定义： 第一个参数是（x轴的开始节点）； 第二个参数是（是y轴的开始节点）； 第三个参数是（是x轴的结束节点）；
                     * 第四个参数是（是y轴的结束节点）； 第五个参数是（是从Excel的第几列开始插入图片，从0开始计数）；
                     * 第六个参数是（是从excel的第几行开始插入图片，从0开始计数）； 第七个参数是（图片宽度，共多少列）；
                     * 第8个参数是（图片高度，共多少行）；
                     */
                    ClientAnchor anchor = drawing.createAnchor(-1, 1, 20, 20, 3 , i1+1,  4, 1);
                    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
                    Picture picture =
                        drawing.createPicture(anchor, workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG));
                    picture.resize();
                    picture.getSheet().setRightToLeft(true);
                   // picture.se(HorizontalAlignment.CENTER);
                    continue;
                }
                if (i2==5){
                    byte[] bytes = getBarCodeByCode(qrMessage1);
                    Drawing drawing = sheet.createDrawingPatriarch();
                    ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5 , i1+1,  6, i1+2);
                    drawing.createPicture(anchor,
                        workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG)).resize();
                    continue;
                }
                cell.setCellValue(i1+"value");
            }

        }
        outputXls(workbook,qrMessage,response);
        //workbook.write(outputStream);
        // 保存Excel文件

        //workbook.close(); // 关闭工作簿

    }

}